{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tracking token usage\n",
    "This notebook goes over how to track your token usage for specific calls.<br>\n",
    "本笔记本介绍了如何跟踪特定调用的令牌使用情况。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using AIMessage.response_metadata"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'token_usage': {'completion_tokens': 191,\n",
       "  'prompt_tokens': 17,\n",
       "  'total_tokens': 208},\n",
       " 'model_name': 'gpt-4-turbo',\n",
       " 'system_fingerprint': 'fp_595e3bc347',\n",
       " 'finish_reason': 'stop',\n",
       " 'logprobs': None}"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4-turbo\")\n",
    "msg = llm.invoke([(\"human\", \"What's the oldest known example of cuneiform\")])\n",
    "msg.response_metadata"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Using callbacks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Tokens Used: 34\n",
      "\tPrompt Tokens: 11\n",
      "\tCompletion Tokens: 23\n",
      "Successful Requests: 1\n",
      "Total Cost (USD): $0.0007999999999999999\n"
     ]
    }
   ],
   "source": [
    "from langchain_community.callbacks.manager import get_openai_callback\n",
    "\n",
    "llm = ChatOpenAI(model=\"gpt-4-turbo\", temperature=0)\n",
    "\n",
    "with get_openai_callback() as cb:\n",
    "    result = llm.invoke(\"Tell me a joke\")\n",
    "    print(cb)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain0_1",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
